package com.factory.test.m5622;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.factory.test.R;
import com.factory.test.base.BaseTestActivity;
import com.factory.test.databinding.ActivityM5622DcBinding;
import com.factory.test.util.FileUtils;
import com.yecontech.sdk.base.gpio.GpioCustom;
import com.yecontech.sdk.base.gpio.YTGpio;
import com.yecontech.sdk.base.gpio.YTGpioStatusListener;

import java.util.Timer;
import java.util.TimerTask;

/**
 * DC 电源检测
 */
public class DCActivity extends BaseTestActivity {

    private ActivityM5622DcBinding binding;
    private GpioCustom dcGpio;
    private GpioCustom dcOnlineGpio;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_m5622_dc);

        dcGpio = sdkService.getGpioCustomManager();
        dcGpio.init("22", 1, new YTGpioStatusListener() {
            @Override
            public void onActive(YTGpio ytGpio, int activeType) {
                handler.post(() -> binding.dc.setChecked(activeType == 1));
            }
        });
        binding.dc.setChecked(dcGpio.getAction() == 1);

        dcOnlineGpio = sdkService.getGpioCustomManager();
        dcOnlineGpio.init("75", 1, new YTGpioStatusListener() {
            @Override
            public void onActive(YTGpio ytGpio, int activeType) {
                handler.post(() -> binding.dcOnline.setChecked(activeType == 0));
            }
        });
        binding.dcOnline.setChecked(dcOnlineGpio.getAction() == 0);

        myTask = new MyTask();
        Timer timer = new Timer();
        timer.schedule(myTask, 1000, 500);
    }

    private MyTask myTask;
    private class MyTask extends TimerTask{
        @Override
        public void run() {
            String node = "/sys/bus/iio/devices/iio:device2/in_voltage1_raw";
            String result = FileUtils.readFile2String(node);
            handler.post(() -> binding.vinAdc.setText("VIN ADC:" + result));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dcGpio.release();
        dcOnlineGpio.release();

        if(myTask != null){
            myTask.cancel();
        }
    }
}
